package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.dto.SysUserInfo;
import com.itheima.ydd.entity.Role;
import com.itheima.ydd.entity.User;
import com.itheima.ydd.service.RoleService;
import com.itheima.ydd.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/sys_user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    public ResultData list(String login_name,String status,String phone,int page,int limit){

        Page<User> userPage=new Page(page,limit);
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(User::getLogin_name,login_name);
        queryWrapper.like(User::getStatus,status);
        queryWrapper.like(User::getPhone,phone);
        queryWrapper.orderByDesc(User::getCreate_date);
        userService.page(userPage,queryWrapper);

        Page<SysUserInfo> userDto =new Page<>();
        BeanUtils.copyProperties(userPage,userDto,"records");
        List<User> records = userPage.getRecords();
        List<SysUserInfo> list=records.stream().map((item->{
            SysUserInfo sysUserInfo=new SysUserInfo();
            BeanUtils.copyProperties(item,sysUserInfo);

            String roleId = item.getRole_id()
                    .replace("[","")
                    .replace("]","")
                    .replace("\"","");
            String[] split = roleId.split(",");

            List<String> ids=new ArrayList<>();
            Collections.addAll(ids,split);
            List<Role> roles = roleService.listByIds(ids);
            List<String> names=roles.stream().map((item2->{
                String name = item2.getName();
                return name;
            })).collect(Collectors.toList());

            sysUserInfo.setRole_id(ids);
            sysUserInfo.setRolename(names);
            return sysUserInfo;

        })).collect(Collectors.toList());

        userDto.setRecords(list);

        PageResult pageResult = PageResult.init(userDto.getTotal(),userDto.getSize(), userDto.getCurrent(), userDto.getRecords());
        return ResultData.ok("",pageResult);

    }

    //修改
    @PostMapping("/update")
    public ResultData updateStatus(@RequestBody SysUserInfo sysUserInfo){
        List<String> roleId = sysUserInfo.getRole_id();

        if (roleId != null) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0; i < roleId.size(); i++) {
            if (i == (roleId.size() - 1)) {
                stringBuffer.append("\"" + roleId.get(i) + "\"");
            } else {
                stringBuffer.append("\"" + roleId.get(i) + "\"" + ",");
            }
        }
        stringBuffer.append("]");
        String roleString = stringBuffer.toString();

        User user = new User();
        user.setId(sysUserInfo.getId());
        user.setLogin_name(sysUserInfo.getLogin_name());
        user.setPassword(sysUserInfo.getPassword());
        user.setName(sysUserInfo.getName());
        user.setEmail(sysUserInfo.getEmail());
        user.setPhone(sysUserInfo.getPhone());
        user.setLogin_ip(sysUserInfo.getLogin_ip());
        user.setCreate_date(sysUserInfo.getCreate_date());
        user.setUpdate_date(sysUserInfo.getUpdate_date());
        user.setDel_flag(sysUserInfo.getDel_flag());
        user.setRole_id(roleString);
        user.setStatus(sysUserInfo.getStatus());
        user.setDefault_data(sysUserInfo.getDefault_data());
        user.setLogin_date(sysUserInfo.getLogin_date());

        userService.updateById(user);

        return ResultData.ok("","修改成功");
        }else {
            User user = userService.getById(sysUserInfo.getId());
            user.setStatus(sysUserInfo.getStatus());
            userService.updateById(user);

            return ResultData.ok("", "修改成功");
        }
    }

    //查询详情
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id){
        User user = userService.getById(id);

        String[] split = user.getRole_id()
                .replace("[","")
                .replace("]","")
                .replace("\"","")
                .split(",");

        List<String> ids=new ArrayList<>();
        Collections.addAll(ids,split);

        SysUserInfo sysUserInfo=new SysUserInfo();
        BeanUtils.copyProperties(user,sysUserInfo);
        sysUserInfo.setRole_id(ids);

        return ResultData.ok("",sysUserInfo);
    }

    //删除
    @GetMapping("/del")
    public  ResultData del(String id){
        userService.removeById(id);
        return ResultData.ok("","删除成功");
    }

    //新增
    @PostMapping("/add")
    public ResultData add(@RequestBody SysUserInfo sysUserInfo){
        List<String> roleId = sysUserInfo.getRole_id();

        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");
        for (int i = 0; i < roleId.size(); i++) {
            if (i == (roleId.size() - 1)) {
                stringBuffer.append("\"" + roleId.get(i) + "\"");
            } else {
                stringBuffer.append("\"" + roleId.get(i) + "\"" + ",");
            }
        }
        stringBuffer.append("]");
        String roleString = stringBuffer.toString();

        User user = new User();

        user.setId(sysUserInfo.getId());
        user.setLogin_name(sysUserInfo.getLogin_name());
        user.setPassword(sysUserInfo.getPassword());
        user.setName(sysUserInfo.getName());
        user.setEmail(sysUserInfo.getEmail());
        user.setPhone(sysUserInfo.getPhone());
        user.setLogin_ip(sysUserInfo.getLogin_ip());
        user.setCreate_date(LocalDateTime.now());
        user.setUpdate_date(LocalDateTime.now());
        user.setDel_flag(sysUserInfo.getDel_flag());
        user.setRole_id(roleString);
        user.setStatus(sysUserInfo.getStatus());
        user.setDefault_data(sysUserInfo.getDefault_data());
        user.setLogin_date(sysUserInfo.getLogin_date());

        userService.save(user);

        return ResultData.ok("","添加成功");
    }
}
